package com.abocode.aichat.server.modules;


import com.abocode.aichat.server.context.channel.ChannelWrapper;
import com.abocode.aichat.exception.NotReadyException;
import com.abocode.aichat.exception.StanzaException;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.context.delivery.reply.Replies;
import com.abocode.aichat.data.MessageStanza;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author guanxf
 */
public abstract class AbstractModuleHandler implements Module<ServerRuntimeContext> {

    private ServerRuntimeContext serverRuntimeContext;
    private Map<String, ModuleServiceHandler> moduleHandlerContext;

    @Override
    public void registerModuleServices(List<ModuleServiceHandler> moduleHandlers) {
        if(moduleHandlers==null ||  moduleHandlers.isEmpty()){
            throw new RuntimeException("moduleHandlers is null");
        }
        moduleHandlerContext=new HashMap<>();
        for(ModuleServiceHandler moduleHandler:moduleHandlers){
            moduleHandlerContext.put(moduleHandler.moduleServiceType().getName(),moduleHandler);
        }
    }

    @Override
    public String name() {
        return modeType().name();
    }

    @Override
    public boolean verify(ChannelWrapper channelWrapper, MessageStanza stanza) {
        if (isChannelReady() && !channelWrapper.isReady()) {
            throw new NotReadyException();
        }
        return name().equals(stanza.name());
    }

    @Override
    public Replies handler(ChannelWrapper channelWrapper, MessageStanza stanza) {
        boolean flag = verify(channelWrapper, stanza);
        if (!flag) {
            throw new StanzaException("stanza is not same");
        }
        return service(channelWrapper, stanza);
    }

    @Override
    public ServerRuntimeContext getServerRuntimeContext() {
        return serverRuntimeContext ;
    }

    @Override
    public void setRuntimeContext(ServerRuntimeContext serverRuntimeContext) {
        this.serverRuntimeContext = serverRuntimeContext;
    }

    @Override
    public Replies service(ChannelWrapper channelWrapper, MessageStanza stanza) {
        String moduleServiceName=stanza.moduleServiceType().name();
        ModuleServiceHandler moduleHandler=moduleHandlerContext.get(moduleServiceName);
        if(moduleHandler==null){
            throw new RuntimeException("moduleHandlers is not found");
        }
        return moduleHandler.execute(channelWrapper, stanza,serverRuntimeContext);
    }

    @Override
    public boolean isChannelReady() {
        return true;
    }
}
